<template>
  <div class="product-add">
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑商品' : '添加商品' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="productForm"
        :rules="rules"
        label-width="120px"
        class="product-form"
      >
        <!-- 基本信息 -->
        <el-divider>基本信息</el-divider>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择商品分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="商品价格" prop="price">
              <el-input-number v-model="productForm.price" :min="0" :precision="2" :step="0.1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品库存" prop="stock">
              <el-input-number v-model="productForm.stock" :min="0" :step="1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品状态" prop="status">
              <el-switch
                v-model="productForm.status"
                :active-value="1"
                :inactive-value="0"
                active-text="上架"
                inactive-text="下架"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品图片 -->
        <el-divider>商品图片</el-divider>
        <el-form-item label="商品主图" prop="picture">
          <el-upload
            class="product-uploader"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="productForm.picture" :src="productForm.picture" class="product-image" />
            <el-icon v-else class="product-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <!-- 商品详情 -->
        <el-divider>商品详情</el-divider>
        <el-form-item label="商品详情" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品详情描述"
          />
        </el-form-item>

        <!-- 规格参数 -->
        <el-divider>规格参数</el-divider>
        <div class="specs-form">
          <div v-for="(spec, index) in productForm.specs" :key="index" class="spec-item">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="'规格名称' + (index + 1)" :prop="'specs.' + index + '.name'">
                  <el-input v-model="spec.name" placeholder="如：颜色" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="'规格值' + (index + 1)" :prop="'specs.' + index + '.value'">
                  <el-input v-model="spec.value" placeholder="如：红色,蓝色,黑色" />
                </el-form-item>
              </el-col>
              <el-col :span="4" class="spec-actions">
                <el-button
                  type="danger"
                  @click="removeSpec(index)"
                  :disabled="productForm.specs.length === 1"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="addSpec">添加规格</el-button>
        </div>

        <!-- 运费设置 -->
        <el-divider>运费设置</el-divider>
        <el-form-item label="运费模板" prop="freightTemplateId">
          <el-select v-model="productForm.freightTemplateId" placeholder="请选择运费模板">
            <el-option
              v-for="item in freightTemplates"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{
            isEdit ? '保存修改' : '添加商品'
          }}</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const isEdit = ref(false)

// 表单数据
const productForm = ref({
  name: '',
  categoryId: '',
  price: 0,
  stock: 0,
  status: 1,
  picture: '',
  description: '',
  specs: [{ name: '', value: '' }],
  freightTemplateId: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  picture: [{ required: true, message: '请上传商品主图', trigger: 'change' }],
  description: [{ required: true, message: '请输入商品详情', trigger: 'blur' }],
  freightTemplateId: [{ required: true, message: '请选择运费模板', trigger: 'change' }]
}

// 模拟数据
const categories = ref([
  { id: 1, name: '手机数码' },
  { id: 2, name: '电脑办公' },
  { id: 3, name: '家用电器' }
])

const freightTemplates = ref([
  { id: 1, name: '包邮模板' },
  { id: 2, name: '统一运费' },
  { id: 3, name: '按重量计费' }
])

// 规格相关方法
const addSpec = () => {
  productForm.value.specs.push({ name: '', value: '' })
}

const removeSpec = (index) => {
  productForm.value.specs.splice(index, 1)
}

// 图片上传相关方法
const handleUploadSuccess = (res) => {
  productForm.value.picture = res.url
  ElMessage.success('上传成功')
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里调用添加或更新商品的API
        const message = isEdit.value ? '商品更新成功' : '商品添加成功'
        ElMessage.success(message)
        router.push('/admin/productlist')
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 如果是编辑模式，获取商品详情
onMounted(async () => {
  const id = route.params.id
  if (id) {
    isEdit.value = true
    // 这里调用获取商品详情的API
    // const res = await getProductDetail(id)
    // productForm.value = res.data
  }
})
</script>

<style scoped>
.product-add {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.product-form {
  max-width: 980px;
  margin: 0 auto;
}

.product-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.product-uploader:hover {
  border-color: #409eff;
}

.product-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.product-image {
  width: 178px;
  height: 178px;
  display: block;
}

.specs-form {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.spec-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #e4e7ed;
}

.spec-actions {
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-divider {
  margin: 24px 0;
}
</style>
